﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using UCL.Powersource;

namespace PowersourceUIToolkit
{
    public static class ViewBinder
    {

        #region ConventionsApplied
        

        public static bool GetConventionsApplied(DependencyObject obj)
        {
            return (bool)obj.GetValue(ConventionsAppliedProperty);
        }

        public static void SetConventionsApplied(DependencyObject obj, bool value)
        {
            obj.SetValue(ConventionsAppliedProperty, value);
        }

        // Using a DependencyProperty as the backing store for ConventionsApplied.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ConventionsAppliedProperty =
            DependencyProperty.RegisterAttached("ConventionsApplied", 
            typeof(bool), 
            typeof(ViewBinder), new PropertyMetadata(false));

        #endregion

        #region ApplyConventions
        public static bool GetApplyConventions(DependencyObject obj)
        {
            return (bool)obj.GetValue(ApplyConventionsProperty);
        }

        public static void SetApplyConventions(DependencyObject obj, bool value)
        {
            obj.SetValue(ApplyConventionsProperty, value);
        }

        // Using a DependencyProperty as the backing store for ApplyConventions.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ApplyConventionsProperty =
            DependencyProperty.RegisterAttached("ApplyConventions", typeof(bool), typeof(ViewBinder), new PropertyMetadata(true));

        #endregion


        public static Action<object, IViewModel> Apply = (v, vm) => ApplyBinding(v, vm);
        
        private static void ApplyBinding(object view, IViewModel viewModel)
        {
            if (view is FrameworkElement)
            {
                var fe = (FrameworkElement)view;
                var ac = ViewBinder.GetApplyConventions(fe);
                if (ac)
                {
                    if (fe.DataContext == null)
                    {
                        fe.DataContext = viewModel;
                    }
                }
            }

        }




    }
}
